package com.sllp.C71S3TsllpShop.web.back;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.sllp.C71S3TsllpShop.bean.Address;
import com.sllp.C71S3TsllpShop.bean.Business;
import com.sllp.C71S3TsllpShop.bean.BusinessExample;
import com.sllp.C71S3TsllpShop.bean.Result;
import com.sllp.C71S3TsllpShop.bean.User;
import com.sllp.C71S3TsllpShop.biz.impl.BusinessBizImpl;
import com.sllp.C71S3TsllpShop.biz.impl.UserBizImpl;
import com.sllp.C71S3TsllpShop.dao.AddressMapper;
import com.sllp.C71S3TsllpShop.dao.BusinessMapper;
import com.sllp.C71S3TsllpShop.util.RandomUtils;
import com.sllp.C71S3TsllpShop.util.SendEmail;

@SessionAttributes({"businessRegisterCode"})
@Controller
public class BackRegisterAction {

	@Resource
	private BusinessBizImpl bbiz;
	@Resource
	private SendEmail sendEmail;
	@Resource
	private UserBizImpl ubiz;
	@Resource
	private BusinessMapper bm;
	@Resource
	private AddressMapper am;
	
	@Value("${spring.resources.staticLocations}")
	private String [] uploadDir;
	
	@GetMapping("back/register")
	public String toRegisterBusiness(Model m,@SessionAttribute("loginUser") User user){
		if(user!=null){
			m.addAttribute("user", user);
		}else{
			return "login";
		}
		return "back/register";
	}
	
	@ResponseBody
	@PostMapping("back/toRegisterNow.do")
	public Result register(@SessionAttribute("loginUser") User user,
			Business business,String addrName,String pwd,String postal,
			String businessRegisterInputCode,Model m,
			@RequestParam("licenceImage") MultipartFile file,
			@SessionAttribute("businessRegisterCode") String businessRegisterCode){
		//TODO 此验证码可改成邮箱验证码
		if(!businessRegisterInputCode.equals(businessRegisterCode)) {
			return new Result(0, "验证码错误");
		}
		String md5Password = DigestUtils.md5DigestAsHex(pwd.getBytes());
		if(!md5Password.equals(user.getPwd())){
			return new Result(0, "用户密码错误");
		}
		String fileName="";
		try {
			String path= uploadDir[0].substring("file:/".length());
			String userFileName=file.getOriginalFilename();
			String suffix = userFileName.substring(userFileName.lastIndexOf('.'));
			String addFileName=String.valueOf(System.currentTimeMillis()).substring(6);
			fileName = "business/licence/"+addFileName+suffix;
			
			//判断文件类型是否正确
			String contentType = file.getContentType();
			String result="";
			if (contentType.equals("image/pjpeg")
					|| contentType.equals("image/jpeg")) {
				// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
			} else if (contentType.equals("image/png")
					|| contentType.equals("image/x-png")) {
				// IE6上传的png图片的headimageContentType是"image/x-png"
			} else if (contentType.equals("image/gif")) {
			} else if (contentType.equals("image/bmp")) {
			} else {
				return new Result(0, "文件类型错误");
			}
			
			File diskFile=new File(path+fileName);
			if (!diskFile.exists()) { // 如果路径不存在，创建
				diskFile.mkdirs();
			}
			file.transferTo(diskFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return new Result(0, "商户准可证上传失败");
		} catch (IOException e) {
			e.printStackTrace();
			return new Result(0, "商户准可证上传失败");
		}
		
		BusinessExample businessExample = new BusinessExample();
		businessExample.createCriteria().andUserEqualTo(user.getId());
		if(bm.selectByExample(businessExample).size()>0){
			return new Result(0, "该账号已注册商家，如非本人操作请联系客服");
		}
		
		Address address=new Address();
		address.setName(addrName);
		address.setPostal(postal);
		address.setTel(user.getTel());
		address.setState(1);
		int flag = am.insertSelective(address);
		if(flag < 1){
			return new Result(0, "添加地址失败");
		}
		business.setUser(user.getId());
		business.setState(1);
		business.setLoginState(2);
		business.setAddr(address.getId());
		business.setLicence(fileName);
		business.setImage(2);
		
		
		Result result1=bbiz.businessRegist(business);
		
		if(result1.getSucess()==0) {
			return result1;
		}
		address.setBusiness(business.getId());
		flag = am.updateByPrimaryKeySelective(address);
		if(flag<1){
			return new Result(0, "添加地址失败");
		}
		return result1;
	}
	
	
	
	
	@Value("${mail.formMail.addr}")
	private String from;
	@Value("${mail.formMail.businessRegisterEmailContent}")
	private String businessRegisterEmailContent;
	
	@ResponseBody
	@PostMapping("back/sendBusinessRegisterEmail.do")
	public Result sendBusinessRegisterEmail(@SessionAttribute("loginUser") User user,Model m){
		// 生成验证码
		String businessRegisterCode = RandomUtils.randomString(4);
		// 将验证码放到session中
		m.addAttribute("businessRegisterCode", businessRegisterCode);
		
		Result resultSendEmail = sendEmail.sendEmail("尤洪商城", from, user.getEmail(), businessRegisterEmailContent, businessRegisterCode,",请妥善保管验证码。");
		return resultSendEmail;
	}

	
//	@PostMapping("back/uploadbusinessimg.do")
//	@ResponseBody
//	public String toUploadImg(Model m,Business business,@RequestParam("image") MultipartFile file,HttpServletRequest request){
//		String path= uploadDir[0].substring("file:/".length());
//		String fileName = "business/licence/"+file.getOriginalFilename();
//		try {
//			if(fileName!=null){
//				business.setLicence(path);
//				path=request.getServletContext().getRealPath(path);
//				File fileObj=new File(path);
//				file.transferTo(fileObj);
//			}
//		} catch (IllegalStateException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	    m.addAttribute("bimg", business);
//		return "back/register";
//	}
	
}
